package com.naqiang.electronicdictionary.fragment;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.naqiang.electronicdictionary.R;
import com.naqiang.electronicdictionary.adapter.OfflineAdapter;
import com.naqiang.electronicdictionary.adapter.TranslateAdapter;
import com.naqiang.electronicdictionary.adapter.UnKnownWordAdapter;
import com.naqiang.electronicdictionary.application.MyApplication;
import com.naqiang.electronicdictionary.data.DBOperationImpl;
import com.naqiang.electronicdictionary.entity.OfflineData;
import com.naqiang.electronicdictionary.entity.TranslateData;
import com.naqiang.electronicdictionary.entity.UnKnowWord;
import com.naqiang.electronicdictionary.util.DateUtil;
import com.naqiang.electronicdictionary.util.LogUtil;
import com.naqiang.electronicdictionary.util.ThreadPoolProxyFactory;
import com.naqiang.electronicdictionary.util.ToastUtil;
import com.naqiang.electronicdictionary.widget.SwListDialog;
import com.youdao.sdk.app.Language;
import com.youdao.sdk.app.LanguageUtils;
import com.youdao.sdk.common.Constants;
import com.youdao.sdk.ydonlinetranslate.Translator;
import com.youdao.sdk.ydtranslate.Translate;
import com.youdao.sdk.ydtranslate.TranslateErrorCode;
import com.youdao.sdk.ydtranslate.TranslateListener;
import com.youdao.sdk.ydtranslate.TranslateParameters;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Author by naqiang, Date on 2019\3\16 0016.
 * PS: Not easy to write code, please indicate.
 * 本类是离线翻译的界面，只支持英文到中文的翻译，因为离线词库只有这个
 */
public class OfflineTranslateFragment extends BaseFragment implements OfflineAdapter.OnOffLineDataListener {

    // 查询列表
    private ListView translateList;
    private OfflineAdapter offlineAdapter;

    private List<OfflineData> list = new ArrayList<>();
    private ProgressDialog progressDialog = null;
    private Handler waitHandler = new Handler();

    private EditText fanyiInputText;

    private InputMethodManager imm;

    private TextView fanyiBtn;

    TextView languageSelectFrom;

    TextView languageSelectTo;

    private Translator translator;

    private DBOperationImpl dbOperation;

    @Override
    protected int setView() {
        return R.layout.fragment_offline_translate;
    }

    @Override
    protected void initView(View view) {
        dbOperation = DBOperationImpl.getInstance();
        fanyiInputText = (EditText) view.findViewById(R.id.fanyiInputText);
        fanyiBtn = (TextView) view.findViewById(R.id.fanyiBtn);
        translateList = (ListView) view.findViewById(R.id.commentList);
        imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        View myview = this.getLayoutInflater().inflate(R.layout.translate_head,
                translateList, false);
        translateList.addHeaderView(myview);
        languageSelectFrom = (TextView) view.findViewById(R.id.languageSelectFrom);
        languageSelectTo = (TextView) view.findViewById(R.id.languageSelectTo);
        offlineAdapter = new OfflineAdapter(list, getActivity());
        offlineAdapter.setOnOffLineDataListener(this);
        translateList.setAdapter(offlineAdapter);
        languageSelectFrom.setText("英文");
        languageSelectTo.setText("中文");
    }

    @Override
    protected void init(Bundle savedInstanceState) {

    }

    @Override
    public void widgetClick(View v) {
        switch (v.getId()) {
            case R.id.fanyiBtn:
                query();
                break;
            case R.id.languageSelectFrom:
                selectLanguage(languageSelectFrom);
                break;
            case R.id.languageSelectTo:
                selectLanguage(languageSelectTo);
                break;
        }
    }

    @Override
    public void setListener() {
        fanyiBtn.setOnClickListener(this);
        //languageSelectFrom.setOnClickListener(this);
        // languageSelectTo.setOnClickListener(this);
    }

    @Override
    public void doWork() {

    }

    /**
     * 选择语种
     *
     * @param languageSelect
     */
    private void selectLanguage(final TextView languageSelect) {
        final String str[] = new String[]{"英文", "中文"};
        List<String> items = new ArrayList<String>();
        for (String s : str) {
            items.add(s);
        }
        SwListDialog exitDialog = new SwListDialog(getActivity(), items);
        exitDialog.setItemListener(new SwListDialog.ItemListener() {

            @Override
            public void click(int position, String title) {

                String language = languageSelect.getText().toString();
                languageSelect.setText(title);
                String from = languageSelectFrom.getText().toString();
                String to = languageSelectTo.getText().toString();
                String lan = "中文";
//                if (!from.contains(lan) && !to.contains(lan)
//                        && !to.contains("自动") && !from.contains("自动")) {
//                    ToastUtils.show("源语言或者目标语言其中之一必须为" + lan);
//                    languageSelect.setText(language);
//                    return;
//                }
            }
        });
        exitDialog.show();
    }

    /**
     * 翻译查询方法
     */
    private void query() {
        showLoadingView("正在查询");

        // 源语言或者目标语言其中之一必须为中文,目前只支持中文与其他几个语种的互译
        String from = "英文";//languageSelectFrom.getText().toString();
        String to = "中文";//languageSelectTo.getText().toString();
        final String input = fanyiInputText.getText().toString();
        final boolean isCH2EN = from.equals("中文") ? true : false;
        refreshListView(input, isCH2EN);
    }

    /**
     * 刷新listView
     */
    private void refreshListView(final String input, final boolean isCH2EN) {
        Observable.create(new ObservableOnSubscribe<OfflineData>() {
            @Override
            public void subscribe(ObservableEmitter<OfflineData> e) {
                OfflineData offlineData = dbOperation.getOfflineUnKnowWord(input, isCH2EN);
                if(offlineData.toWord==null){
                    ToastUtil.showToast("离线词典未查找到！");
                    return;
                }
                LogUtil.i("ccccccc", offlineData.toString());
                e.onNext(offlineData);
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<OfflineData>() {

                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(OfflineData offlineData) {
                        list.add(offlineData);
                        offlineAdapter.notifyDataSetChanged();
                        translateList.smoothScrollToPosition(list.size()-1);
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    /**
     * 显示加载中视图
     *
     * @param text
     */
    private void showLoadingView(final String text) {
        waitHandler.post(new Runnable() {

            @Override
            public void run() {
                if (progressDialog != null && !progressDialog.isShowing()) {
                    progressDialog.setMessage(text);
                    progressDialog.show();
                }
            }
        });

    }

    /**
     * 隐藏加载视图
     */
    private void dismissLoadingView() {
        waitHandler.post(new Runnable() {

            @Override
            public void run() {
                if (progressDialog != null && progressDialog.isShowing())
                    progressDialog.dismiss();
            }
        });

    }

    public void postQuery(final Translate bean) {
        showLoadingView("正在翻译，请稍等");
    }

    /**
     * 当加入单词本几个字被点击回调此方法
     *
     * @param position
     * @param textView
     */
    @Override
    public void onOffLineDataAddNote(final int position, TextView textView) {
        if(textView!=null){
            textView.setVisibility(View.GONE);
        }
        ThreadPoolProxyFactory.getNormalThreadPoolProxy().execute(new Runnable() {
            @Override
            public void run() {
                OfflineData bean = list.get(position);
                UnKnowWord unKnowWord = new UnKnowWord();
                unKnowWord.fromLanguage = languageSelectFrom.getText().toString();
                unKnowWord.toLanguage = languageSelectTo.getText().toString();
                unKnowWord.fromWord = bean.fromWord;
                unKnowWord.toWord = bean.toWord;
                unKnowWord.addTime = DateUtil.getCurrentDateStr();
                boolean flag = dbOperation.insertUnKnowWord(unKnowWord);
                LogUtil.i("unKnowWord.toString", unKnowWord.toString() + flag);
            }
        });
    }
}
